package com.zjdiepu.www.biz.dh;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.status.ExpressStatus;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.lang.HttpClientException;
import com.zjdiepu.www.common.util.ZhppDateUtil;
import com.zjdiepu.www.dao.dh.DhOverdueLetterLawyersMapper;
import com.zjdiepu.www.dao.other.OtherExpressMapper;
import com.zjdiepu.www.ibiz.dh.IDhOverdueLetterLawyersService;
import com.zjdiepu.www.ibiz.third.net.IDeliverService;
import com.zjdiepu.www.model.dh.dto.DhOverdueLetterLawyers;
import com.zjdiepu.www.model.dh.ext.DhOverdueLetterLawyersExt;
import com.zjdiepu.www.model.other.dto.OtherExpress;
import com.zjdiepu.www.model.third.request.ali.AliDeliverRequest;
import com.zjdiepu.www.model.third.response.ali.AliDeliverResponse;
import com.zjdiepu.www.model.third.response.ali.DeliverShowApiResBody;
import com.zjdiepu.www.model.third.response.ali.DeliverTrace;
import com.zjdiepu.www.util.CachedEnums;
import com.zjdiepu.www.util.ExceptionHelper;

/**
 * 逾期_律师函Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年04月21日 14时14分<br/>
 * @since 1.0<br/>
 */
@Service
public class DhOverdueLetterLawyersServiceImpl extends BaseService implements IDhOverdueLetterLawyersService {
	public static final Logger logger = LoggerFactory.getLogger(DhOverdueLetterLawyersServiceImpl.class);
	
	@Resource(name = "aliDeliverServiceImpl")
	private IDeliverService<AliDeliverRequest, AliDeliverResponse> deliverService;
	
	@Autowired
	private DhOverdueLetterLawyersMapper dhOverdueLetterLawyersMapper;
	
	@Autowired
	private OtherExpressMapper otherExpressMapper;

	@Override
	public void saveUpdateAndDelete(DhOverdueLetterLawyers dhOverdueLetterLawyers, OperateType operType) {
		switch (operType) {
		case add:
			dhOverdueLetterLawyers.initInsertData(dhOverdueLetterLawyers.getModifier(), dhOverdueLetterLawyers.getModifierName());
			try {
				dhOverdueLetterLawyers.setCreated(ZhppDateUtil.dateConvertTimeStamp(dhOverdueLetterLawyers.getJbTime(), "yyyy-MM-dd"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			dhOverdueLetterLawyersMapper.insert(dhOverdueLetterLawyers);
			break;
		case edit:
			dhOverdueLetterLawyers.initUpdateData(dhOverdueLetterLawyers.getModifier(), dhOverdueLetterLawyers.getModifierName());
			// 影响的记录数
			int updateCount = dhOverdueLetterLawyersMapper.updateByPrimaryKeySelective(dhOverdueLetterLawyers);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			dhOverdueLetterLawyers.initDeleteData(dhOverdueLetterLawyers.getModifier(), dhOverdueLetterLawyers.getModifierName());
			// 影响的记录数
			int deleteCount = dhOverdueLetterLawyersMapper.updateByPrimaryKeySelective(dhOverdueLetterLawyers);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<DhOverdueLetterLawyers> selectByExt(DhOverdueLetterLawyersExt dhOverdueLetterLawyersExt) {
		return dhOverdueLetterLawyersMapper.selectByExt(dhOverdueLetterLawyersExt);
	}
	
	@Override
	public int countByExt(DhOverdueLetterLawyersExt dhOverdueLetterLawyersExt){
		return dhOverdueLetterLawyersMapper.countByExt(dhOverdueLetterLawyersExt);
	}
	
	@Override
	public DhOverdueLetterLawyers selectById(String id) {
		return dhOverdueLetterLawyersMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			dhOverdueLetterLawyersMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(DhOverdueLetterLawyers dhOverdueLetterLawyers) {
		return dhOverdueLetterLawyersMapper.countRefined(dhOverdueLetterLawyers);
	}

	@Override
	public DhOverdueLetterLawyers selectRefined(DhOverdueLetterLawyers dhOverdueLetterLawyers) {
		return dhOverdueLetterLawyersMapper.selectRefined(dhOverdueLetterLawyers);
	}

	@Override
	public boolean repeat(DhOverdueLetterLawyers dhOverdueLetterLawyers) {
		int count = countRefined(dhOverdueLetterLawyers);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(dhOverdueLetterLawyers.getId())) {
			return true;
		}
		DhOverdueLetterLawyers dbItem = selectRefined(dhOverdueLetterLawyers);
		if(null == dbItem) {
			return false;
		}
		return !dhOverdueLetterLawyers.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return dhOverdueLetterLawyersMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}

	@Override
	public boolean deleteByNoExpress(String noExpress) {
		return dhOverdueLetterLawyersMapper.deleteByNoExpress(noExpress);
	}

	@Override
	public DhOverdueLetterLawyers selectByNoExpress(String noExpress) {
		return dhOverdueLetterLawyersMapper.selectByNoExpress(noExpress);
	}

	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, timeout = 60)
	public String saveExpress(String nu, AbstractSysUser currentUser) {
    	try {
    		AliDeliverRequest aliDeliverRequest = new AliDeliverRequest();
    		aliDeliverRequest.setNu(nu);
    		AliDeliverResponse deliverResponse = deliverService.saveExpInfo(nu, null);//结果已经完成验证
			DeliverShowApiResBody showapiResBody = deliverResponse.getShowapiResBody();
			String status = showapiResBody.getStatus().toString();
			DhOverdueLetterLawyers cachedOverdueLetterLawyers = dhOverdueLetterLawyersMapper.selectByNoExpress(nu);
			if(null != cachedOverdueLetterLawyers) {
				if(status.equals(cachedOverdueLetterLawyers.getStatusExpress())) { //律师函状态没变，不需要再次保存
					return cachedOverdueLetterLawyers.getId();
				} else {
					dhOverdueLetterLawyersMapper.deleteByNoExpress(nu);
					otherExpressMapper.deleteByLetterLawyersId(cachedOverdueLetterLawyers.getId());
				}
			}
			DhOverdueLetterLawyers dhOverdueLetterLawyers = new DhOverdueLetterLawyers();
			dhOverdueLetterLawyers.initInsertData(currentUser.getId(), currentUser.getName());
			dhOverdueLetterLawyers.setNoExpress(showapiResBody.getMailNo());
			dhOverdueLetterLawyers.setCompanyExpress(showapiResBody.getExpTextName());
			dhOverdueLetterLawyers.setStatusExpress(status);
			dhOverdueLetterLawyers.setStatusNameExpress((String)CachedEnums.getValue(status, ExpressStatus.class));
			dhOverdueLetterLawyersMapper.insert(dhOverdueLetterLawyers);
			
			Boolean flag = showapiResBody.getFlag();
			if (null != flag && flag) {
				List<DeliverTrace> data = showapiResBody.getData();
				if (CollectionUtils.isNotEmpty(data)) {
					List<OtherExpress> otherExpresses = new ArrayList<OtherExpress>();
					for (DeliverTrace deliverTrace : data) {
						OtherExpress otherExpress = new OtherExpress();
						otherExpress.initInsertData(currentUser.getId(), currentUser.getName());
						otherExpress.setLetterLawyersId(dhOverdueLetterLawyers.getId());
						otherExpress.setTimeExpress(deliverTrace.getTime());
						otherExpress.setContexttExpress(deliverTrace.getContext());
						
						otherExpresses.add(otherExpress);
					}
					otherExpressMapper.insertBatch(otherExpresses);
				}
			}
			
			return dhOverdueLetterLawyers.getId();
		} catch (HttpClientException e) {
			ExceptionHelper.thow(String.valueOf(e.getHttpStatusCode()), e.getMessage());
			return null;
		} catch (SocketTimeoutException e) {
			ExceptionHelper.thow(ResultFlagType.FAIL, e);
			return null;
		}
	}

	@Override
	public List<DhOverdueLetterLawyers> selectCountByLawyers(String value1) {
		return dhOverdueLetterLawyersMapper.selectCountByLawyers(value1);
	}
}
